package net.howson.phil.datahiding.stream;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

public class ComponentOutputStream extends OutputStream {

	private final BufferedImage image;
	private final int actualWidth;
	private final int height;
	private final int[] components = new int[3];

	private int width;
	private int x;
	private int y;
	private int offsetX;

	private int cursor = 0;

	public ComponentOutputStream(BufferedImage image, int reps) {
		this.image = image;
		this.actualWidth = image.getWidth();
		this.width = actualWidth / reps;
		this.height = image.getHeight();

	}

	@Override
	public void write(int b) throws IOException {
		components[cursor++] = b;
		if (cursor == components.length) {
			image.setRGB(x + offsetX, y, (components[0] << 16) | (components[1] << 8) | components[2]);			
			
			cursor = 0;
			if (++x >= width) {
				x = 0;
				if (++y >= height) {
					y = 0;
					offsetX += width;
				}
			}			
		}
	}

}
